import 'package:flutter/material.dart';
import 'package:track_demo/gesture/custom_gesturedetector.dart';
import 'package:track_demo/util/md5.dart';

void main() => runTyApp();

var binding = WidgetsFlutterBinding.ensureInitialized();

runTyApp() {
  return binding
    ..scheduleAttachRootWidget(MyApp())
    ..scheduleWarmUpFrame();
}

RouterTrackObserver pageObserver;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Listener(
      behavior: HitTestBehavior.opaque,
      onPointerDown: (details) {
//        print("全局手势监听$details");
      },
      child: TYPage(
        child: TYTrack(
          tapCallback: (path) {
//          print("唯一值：" + path);
          },
          child: MaterialApp(
            title: 'Track Demo',
            home: ListPage(),
            routes: {
              'home': (context) => MyHomePage(),
              'list': (context) => ListPage()
            },
            navigatorObservers: [
              RouterTrackObserver(
                pvEventTrancking: (pageName) {
                  print("pageName:$pageName");
                },
              ),
              routeObserver
            ],
          ),
        ),
      ),
    );
  }
}

BuildContext routeContext; // 当页面didPush和didPop的时候，会初始化该值
String routePagePath; // 最新获取到的部分路由path
bool shouldVisit = false; // 是否继续遍历，这边到Scaffold停止，后面的path对PV唯一值没有影响
bool isFullPage = false; // 是否是全屏页面
List<String> pathList = List(); //自己维护的路由表
bool isPush = false; // 是否是push操作

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

// OUTER PAGE

class TYPage extends StatefulWidget {
  final Widget child;

  TYPage({this.child});

  @override
  _TYPageState createState() => _TYPageState();
}

class _TYPageState extends State<TYPage> with WidgetsBindingObserver, RouteAware{
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPersistentFrameCallback((ts) {
      if (isPush) {
        shouldVisit = true;
        routePagePath = "";
        if (null != routeContext) {
          routeContext.visitChildElements(_visitor);
        }
//      routePagePath = generateMd5(routePagePath);
        if (pathList.length == 0 || pathList.last != routePagePath) {
          print("页面PUSH：" + routePagePath);
          pathList.add(routePagePath);
        }
        routePagePath = "";
      }
    });
  }

  void _visitor(Element element) {
    if (shouldVisit) {
      if (element.widget is Scaffold) {
        shouldVisit = false;
      }
      routePagePath += "->" + element.widget.runtimeType.toString();
      element.visitChildElements(_visitor);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("${state}");
  }

  @override
  void setState(fn) {
    super.setState(fn);
    routeObserver.subscribe(this, ModalRoute.of(context));
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void didPush() {
    super.didPush();
//    print("---------++:${ModalRoute.of(context).opaque}");

  }

  @override
  void didPop() {
    super.didPop();
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

// PAGE..

class MyHomePage extends StatefulWidget {
  final String title = "MyHomePage";

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((ts) {
//      print("第1帧渲染完成");
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("state ---> $state");
    super.didChangeAppLifecycleState(state);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: GestureDetector(
          onTap: () {},
          child: Text(widget.title),
        )),
        body: Center(
          child: GestureDetector(
            onTap: () {
              showDialog1();
//            print("第1层点击${DateTime.now()}");
            },
            child: Container(
              width: 300,
              height: 300,
              color: Color.fromRGBO(0, 0, 0, 0.1),
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) => ListPage(),
                          settings: RouteSettings(name: "mList")));
//                  Navigator.pushNamed(context, 'list');
//                print("第2层点击${DateTime.now()}");
                },
                child: Container(
                  width: 100,
                  height: 100,
                  color: Color.fromRGBO(0, 0, 0, 0.4),
                  alignment: Alignment.center,
                  child: RaisedButton(
                    onPressed: () {
//                      print("第3层点击${DateTime.now()}");
                    },
                    child: Text("MyHomePage"),
                  ),
                ),
              ),
            ),
          ),
        ));
  }

  void showDialog1() {
    showDialog<Null>(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('选择'),
          children: <Widget>[
            new SimpleDialogOption(
              child: new Text('选项 1'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            new SimpleDialogOption(
              child: new Text('选项 2'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    ).then((val) {
      print(val);
    });
  }
}

class ListPage extends StatelessWidget {
  List list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      appBar: AppBar(title: Text("我是标题栏"),
//          actions: <Widget> [
//            IconButton(
//              icon: Icon(Icons.alarm),
//              tooltip: "Alarm",
//              onPressed: () {
//                print("Alarm");
//              },
//            ),
//          ],),
      body: SingleChildScrollView(
        child: Column(
          children: list.map((itemIndex) {
            return GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, 'home');
              },
              child: Container(
                height: 150,
                width: double.infinity,
                margin: EdgeInsets.only(top: 20),
                color: Colors.grey,
                alignment: Alignment(0.92, 0.1),
                child: Text("$itemIndex"),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}
